//
//  OpenCourseViewController.m
//  xpkc
//
//  Created by TopSageOSX on 14/12/18.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "OpenCourseViewController.h"
#import "RefreshView.h"


typedef NS_ENUM(int, ClassType) {
    ClassTypeEnglish,
    ClassTypeAccount,
    ClassTypeEngineering
};

@interface OpenCourseViewController ()
{
	UIScrollView *scrollView;
	NSMutableArray *catalogueArray;
	NSMutableArray *btnArray;
	CGPoint startPoint;
	UIButton *tempBtn;
	CGRect tempFrame;
	CGFloat xx;//偏移距离
	CGFloat yy;
	int xP;//偏移单位
	int yP;
	int startIndex;//起始按钮数组位置
	int stopIndex;
    int btnP;//按钮当前位置
	CGFloat buttonW;//按钮宽度
	CGFloat buttonH;
	int numLine;//每行个数
	CGFloat spaceSize;//间隔大小
   
	
}
@end

@implementation OpenCourseViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.navigationItem.title = @"公开课";
        self.tabBarItem.title = @"公开课";
        self.tabBarItem.image = [UIImage imageNamed:@"tab_open"];
        if (IsIOS7) {
            self.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_open_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        }
    }
    return self;
}
/**
 *  创建视图
 */
-(void)creatView{
	if (isPad) {
		spaceSize = 40;
		numLine = 3;
	}else{
		spaceSize = 0;
		numLine = 3;
	}
	buttonW = (SCREEN_WIDTH-spaceSize*(numLine+1))/numLine;
    buttonH = buttonW*1;
	
	scrollView = [[UIScrollView alloc]init];
	scrollView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-self.tabBarController.tabBar.frame.size.height);
	
	scrollView.showsVerticalScrollIndicator = FALSE;
	scrollView.backgroundColor = BGColor;
	scrollView.userInteractionEnabled = YES;
	btnArray = [NSMutableArray array];
	[self.view addSubview:scrollView];
	//开始获取
	[self getLocalCatelogueInfo];
}
/**
 *  界面赋值
 */
-(void)setViewValue:(int)local{
	scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, (catalogueArray.count+1)/2*(buttonH+spaceSize)+spaceSize);
	[btnArray removeAllObjects];
//    NSLog(@"%ld",catalogueArray.count);
	for (int i = 0; i<catalogueArray.count; i++) {
		//信息
		NSDictionary *dic = [catalogueArray objectAtIndex:i];
//        NSString *courseName = [dic objectForKey:@"TypeName"];
        NSString *courseID = [dic objectForKey:@"id"];
        //按钮
		UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        //ClassType classType;
		if (local == 0) { // 本地不存在
            
            //配色
//            if ([courseName rangeOfString:@"英语"].location != NSNotFound) {
//                classType = ClassTypeEnglish;
//            }else if([courseName rangeOfString:@"会计"].location != NSNotFound){
//                classType = ClassTypeAccount;
//            }else if([courseName rangeOfString:@"建造"].location != NSNotFound){
//                classType = ClassTypeEngineering;
//            }
			//保存
			NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithDictionary:dic];
			//[newDic setValue:[NSString stringWithFormat:@"%d",classType] forKey:@"classType"];
            [newDic setValue:[NSString stringWithFormat:@"%d",i] forKey:@"imageID"];
			[catalogueArray setObject:newDic atIndexedSubscript:i];
            
		}else{
            
//            classType = [[dic objectForKey:@"classType"]intValue];
		}
//        UIColor *bgColor;
//        NSString *classTypeStr;
//        UIImage *classTypeImg;
//        switch (classType) {
//            case ClassTypeAccount:
//            {
//                bgColor = UIColorFromRGB(0x0eadc0);
//                classTypeStr = @"财会类";
//                classTypeImg = [UIImage imageNamed:@"Accounting"];
//            }
//                break;
//            case ClassTypeEnglish:
//            {
//                bgColor = UIColorFromRGB(0xfc7087);
//                classTypeStr = @"外语类";
//                classTypeImg = [UIImage imageNamed:@"English"];
//            }
//                break;
//            case ClassTypeEngineering:
//            {
//                bgColor = UIColorFromRGB(0x4ea0e4);
//                classTypeStr = @"工程类";
//                classTypeImg = [UIImage imageNamed:@"Engineering"];
//            }
//                break;
//                
//            default:
//                break;
//        }
      
        
        button.backgroundColor = BGColor;
        
        // 添加标题类型label
//        UILabel *classTypeLabel =[[UILabel alloc]initWithFrame:CGRectMake(10, 0, buttonW*2/3, buttonW*0.25)];
//        classTypeLabel.text = classTypeStr;
//        classTypeLabel.textColor = [UIColor whiteColor];
//        [button addSubview:classTypeLabel];
        
        // 添加button图片
        //UIImageView *typeImg = [[UIImageView alloc]initWithFrame:CGRectMake(buttonW*0.75-5, 5, buttonW*0.25, buttonW*0.25)];
        UIImageView *typeImg = [[UIImageView alloc]initWithFrame:CGRectMake(buttonW*1/3, 15, buttonW*0.35, buttonW*0.35)];
        //typeImg.image = classTypeImg;
//        NSLog(@"%@",[NSString stringWithFormat:@"OpenCourseCategoryBtn_0%@",catalogueArray[i][@"imageID"]]);
        typeImg.image = [UIImage imageNamed:[NSString stringWithFormat:@"OpenCourseCategoryBtn_0%@",catalogueArray[i][@"imageID"]]];
        [button addSubview:typeImg];
        
        
		button.frame = CGRectMake(i%numLine*(buttonW+spaceSize)+spaceSize, i/numLine*(buttonH+spaceSize)+spaceSize, buttonW, buttonH);
		[button setTitleEdgeInsets:UIEdgeInsetsMake(buttonW*0.25, 5, 0, 5)];
		if (isPad) {
			button.titleLabel.font = [UIFont boldSystemFontOfSize:20];
		}else{
			button.titleLabel.font = [UIFont boldSystemFontOfSize:13];
		}
        //button.backgroundColor = [UIColor redColor];
        button.layer.cornerRadius = 3;
		button.titleLabel.numberOfLines = 0;
        //button.titleLabel.backgroundColor = [UIColor yellowColor];
        button.tag = [courseID intValue];
		[button setTitle:[dic objectForKey:@"TypeName"] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
		[button addTarget:self action:@selector(catalogueButtonClick:) forControlEvents:UIControlEventTouchUpInside];
		UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(touchesMove:)];
		[button addGestureRecognizer:longPress];
		[scrollView addSubview:button];
		[btnArray addObject:button];
	}
   
}
/**
 *  创建导航栏按钮
 */
- (void)creatNavigationItem{
    //无返回，重写
    UIBarButtonItem *manageBtn = [[UIBarButtonItem alloc]initWithTitle:@"更新" style:UIBarButtonItemStyleBordered target:self action:@selector(catalogueManager)];
    [manageBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,[UIFont systemFontOfSize:16.0], NSFontAttributeName, nil] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = manageBtn;
}
/**
 *  获取目录信息
 */
-(void)getCatalogueInfo{
    
    

    NSString *module = @"openCourse";
    NSString *interface = @"columnlist";
    
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    
    NSDictionary *parameter = @{@"time":timeString};
   
    
    
    
	//POST请求
	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
	manager.responseSerializer = [AFHTTPResponseSerializer serializer];
	[manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
		NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        //logdebug(@"%@",dic);
		/**
		 *  判断发送请求的格式是否正确，不正确的话返回的参数是比较蛋疼的
		 */
		if ([dic objectForKey:@"timerror"]) {
			logdebug(@"faterror:退出登录");
			[UserMessage sharedUserMessage].isLogin = NO;
			UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请确保手机时间与北京时间相差五分钟以内" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
			[alert show];
			return ;
		}
		catalogueArray = [NSMutableArray arrayWithArray:[dic objectForKey:@"info"]];
		[self setViewValue:0];
        
        
	} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    
        
        
	}];
}
/**
 *  获取本地的目录信息
 */

-(void)getLocalCatelogueInfo{
	catalogueArray= [NSMutableArray arrayWithContentsOfFile:CATAGOLUE_PATH];
	if (catalogueArray.count!=0) {
		//
		logdebug(@"本地已有");
		[self setViewValue:1];
	}else{
		//请求网络的时候以后修改
		[self getCatalogueInfo];
	}
}


- (void)viewDidLoad
{
	[super viewDidLoad];
	if (IsIOS7) {
		[self setEdgesForExtendedLayout:UIRectEdgeNone];
	}
	
    
   
	[self creatView];
}
/**
 *  项目按钮点击
 *
 *  @param btn btn
 */
-(void)catalogueButtonClick:(UIButton *)btn{
	//logdebug(@"%d%@",btn.tag,btn.titleLabel.text);
	//TODO:界面跳转
	ListenTestViewController *listenTest = [[ListenTestViewController alloc]init];
	listenTest.typeId = btn.tag;
    listenTest.className = btn.titleLabel.text;
	[listenTest setTitle:[NSString stringWithFormat:@"%@公开课",btn.titleLabel.text]];
	[self.navigationController pushViewController:listenTest animated:YES];
	//自定义返回钮也能够左拉返回
	if (IsIOS7) {
		if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
			self.navigationController.interactivePopGestureRecognizer.delegate = nil;
		}
	}
}

/**
 *  长按手势新
 *
 *  @param ges ges
 */
- (void)touchesMove:(UIGestureRecognizer *)ges{
    if (ges.state == UIGestureRecognizerStateBegan) {
        startPoint = [ges locationInView:scrollView];
        logdebug(@"%f:%f",startPoint.x,startPoint.y);
        btnP = ((int)startPoint.x/(int)(SCREEN_WIDTH/numLine)*1+(int)startPoint.y/(int)(buttonH+spaceSize)*numLine);
        tempBtn = [btnArray objectAtIndex:btnP];
        tempBtn.layer.shadowColor = [UIColor blackColor].CGColor;
        tempBtn.layer.shadowOffset = CGSizeMake(10, 10);
        tempBtn.layer.shadowOpacity = 0.4;
        [scrollView bringSubviewToFront:tempBtn];
        tempFrame = tempBtn.frame;
    }else if(ges.state == UIGestureRecognizerStateChanged) {
        CGPoint point = [ges locationInView:scrollView];
        logdebug(@"%f:%f",point.x,point.y);
        tempBtn.frame = CGRectMake(tempFrame.origin.x + point.x - startPoint.x, tempFrame.origin.y + point.y - startPoint.y, buttonW, buttonH);
        int currentP = ((int)point.x/(int)(SCREEN_WIDTH/numLine)*1+(int)point.y/(int)(buttonH+spaceSize)*numLine);
        if (currentP >= btnArray.count) {
            currentP = btnArray.count -1;
        }
        if (currentP < 0) {
            currentP = 0;
        }
        if (currentP == btnP) {
        }else{
            if (currentP < btnP) {
                [btnArray insertObject:[btnArray objectAtIndex:btnP] atIndex:currentP];
                [btnArray removeObjectAtIndex:btnP+1];
                [catalogueArray insertObject:[catalogueArray objectAtIndex:btnP] atIndex:currentP];
                [catalogueArray removeObjectAtIndex:btnP+1];
                
                for (int i = currentP+1; i<=btnP; i++) {
                    UIButton *btn = [btnArray objectAtIndex:i];
                    [UIView beginAnimations:nil context:nil];
                    [UIView setAnimationDuration:0.4];
                    [UIView setAnimationDelay:(i-currentP)*0.2];
                    btn.frame = CGRectMake((i)%numLine*(buttonW+spaceSize)+spaceSize, (i)/numLine*(buttonH+spaceSize)+spaceSize, buttonW, buttonH);
                    [UIView commitAnimations];
                }
            }else{
                [btnArray insertObject:[btnArray objectAtIndex:btnP] atIndex:currentP+1];
                [btnArray removeObjectAtIndex:btnP];
                [catalogueArray insertObject:[catalogueArray objectAtIndex:btnP] atIndex:currentP+1];
                [catalogueArray removeObjectAtIndex:btnP];
                
                for (int i = btnP; i<currentP; i++) {
                    UIButton *btn = [btnArray objectAtIndex:i];
                    [UIView beginAnimations:nil context:nil];
                    [UIView setAnimationDuration:0.4];
                    [UIView setAnimationDelay:(i-btnP)*0.2];
                    btn.frame = CGRectMake(i%numLine*(buttonW+spaceSize)+spaceSize, i/numLine*(buttonH+spaceSize)+spaceSize, buttonW, buttonH);
                    [UIView commitAnimations];
                }
            }
            btnP = currentP;
        }
    }else if (ges.state == UIGestureRecognizerStateEnded){
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.4];
        tempBtn.frame = CGRectMake(btnP%numLine*(buttonW+spaceSize)+spaceSize, btnP/numLine*(buttonH+spaceSize)+spaceSize, buttonW, buttonH);
        tempBtn.layer.shadowOffset = CGSizeMake(0, 0);
        [UIView commitAnimations];
    }
}

-(void)viewWillDisappear:(BOOL)animated{
	logdebug(@"视图消失:保存目录信息");
	//TODO:保存排列好的标签顺序
	logdebug(@"保存完成:%d",
    [catalogueArray writeToFile:CATAGOLUE_PATH atomically:YES]);
	[catalogueArray writeToFile:CATAGOLUE_PATH atomically:YES];
	//    logdebug(@"保存位置:%@",DOC_PATH);
}
/**
 *  目录管理
 */
-(void)catalogueManager{
	logdebug(@"目录管理");
	//TODO:1刷新列表2删除或者修改列表
	for (UIButton *btn in btnArray) {
		[btn removeFromSuperview];
	}
	[self getCatalogueInfo];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (BOOL)shouldAutorotate{
    return NO;
}
- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
